# -*- coding:utf-8 -*-
import re
import requests
import json

"""
从百度上下载图片
"""
def download_pic(html, keyword):
    pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
    i = 1
    print('找到关键词:' + keyword + '的图片，现在开始下载图片...')
    for each in pic_url:
        print('正在下载第' + str(i) + '张图片，图片地址:' + str(each))
        try:
            pic = requests.get(each, timeout=10)
        except requests.exceptions.ConnectionError:
            print('【错误】当前图片无法下载')
            continue

        dir = 'H:/test/' + keyword + '_' + str(i) + '.jpg'
        fp = open(dir, 'wb')
        fp.write(pic.content)
        fp.close()
        i += 1


if __name__ == '__main__':
    # word = input("证件照蓝底图片纯图")
    # url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&ct=201326592&v=flip'
    url = 'https://image.baidu.com/search/index?ct=201326592&cl=2&st=-1&lm=-1&nc=1&ie=utf-8&tn=baiduimage&ipn=r&rps=1&pv=&fm=rs3&word=%E8%AF%81%E4%BB%B6%E7%85%A7%E8%93%9D%E5%BA%95%E5%9B%BE%E7%89%87%E7%BA%AF%E5%9B%BE&oriquery=%E8%93%9D%E5%BA%95%E5%B7%A5%E8%A3%85%E8%AF%81%E4%BB%B6%E7%85%A7%E7%BE%8E%E5%A5%B3&ofr=%E8%93%9D%E5%BA%95%E5%B7%A5%E8%A3%85%E8%AF%81%E4%BB%B6%E7%85%A7%E7%BE%8E%E5%A5%B3&hs=2&sensitive=0'
    result = requests.get(url)
    download_pic(result.text, '证件照蓝底图片纯图')
    for x in range(10):
        pn = (x + 1) * 30
        url1 = 'https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E8%93%9D%E5%BA%95%E8%AF%81%E4%BB%B6%E7%85%A7%E7%BE%8E%E5%A5%B3&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&word=%E8%93%9D%E5%BA%95%E8%AF%81%E4%BB%B6%E7%85%A7%E7%BE%8E%E5%A5%B3&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&pn=' + pn + '&rn=30&gsm=1e&1532683939720='
        result = requests.get(url1)
        batch_download_pic(result.text, 3134000027, "初中", 2019, 1)
